<?php


namespace app\common\library;

use common;
use hiredis;
use vtimer;

class XiaoAnEcuModel
{

    var $xc_access_token = 'F82DFAFCACD3F69BEB2276CA7CC76B9B';
    var $agent_id = 313;

    var $imeis_in_test = [
        // '869270049337826',
        // '869270049330235',
        '866039041762239'
    ];

    function code_to_msg($code)
    {

        $code_eror_msg = [
            100 => [ECU_ERROR_500, 'ECU服务器内部错误'],
            101 => [ECU_ERROR_500, '请求无IMEI'],
            103 => [ECU_ERROR_500, '无请求内容'],
            104 => [ECU_ERROR_500, '请求URL错误'],
            105 => [ECU_ERROR_500, '请求范围过大'],
            106 => [ECU_ERROR_500, '接入服务器无响应'],
            107 => [ECU_ERROR_500, '接入服务器不在线'],
            108 => [ECU_ERROR_TIMEOUT, '设备无响应'],
            109 => [ECU_ERROR_OFFLINE, '设备离线'],
            132 => [ECU_ERROR_IN_MOTION, '运动中'],
            0 => [0, 'OK'],
        ];

        if (isset($code_eror_msg[$code])) {
            return $code_eror_msg[$code];
        }
        return [ECU_ERROR_500, '未知错误'];
    }

    function get_xc_access_token($imei)
    {
        if (in_array($imei, $this->imeis_in_test)) {
            return '525511E04347F12AE6C5D74D705DD84A';
        }
        return $this->xc_access_token;
    }

    function get_agent_id($imei)
    {
        if (in_array($imei, $this->imeis_in_test)) {
            return 87;
        }
        return $this->agent_id;
    }

    function xiao_an_ecu_lock($imei)
    {
        $vt = new vtimer();
        $hs = [
            'Content-Type: application/json',
            'xc-access-token:' . $this->get_xc_access_token($imei),
        ];

        $url = 'https://api.xiaoantech.com/ebike/v1/lock';
        $postdata = [
            'imei' => $imei,
            'locked' => 1,
            'agentId' => $this->get_agent_id($imei),
            'sn' => common::sn(),
        ];
        $result = common::curlpostjson($url, $postdata, $hs);
        if (empty($result)) {
            return [-1, "request error!", $vt->cost()];
        }

        if ($result['success'] == true) {
            if (isset($result['data']) && isset($result['data']['code'])) {
                list($code, $msg) = $this->code_to_msg($result['data']['code']);
                return [$code, $msg, $vt->cost()];
            }
        }

        return [-2, '请重试！', $vt->cost()];
    }

    function xiao_an_ecu_acc_off($imei)
    {
        $vt = new vtimer();
        $hs = [
            'Content-Type: application/json',
            'xc-access-token:' . $this->get_xc_access_token($imei),
        ];

        $url = 'https://api.xiaoantech.com/ebike/v1/acc';
        $postdata = [
            'imei' => $imei,
            'acc' => 0,
            'agentId' => $this->get_agent_id($imei),
            'sn' => common::sn(),
        ];

        $result = common::curlpostjson($url, $postdata, $hs);
        if (empty($result)) {
            return [-1, "request error!", $vt->cost()];
        }

        if ($result['success'] == true) {
            if (isset($result['data']) && isset($result['data']['code'])) {
                list($code, $msg) = $this->code_to_msg($result['data']['code']);
                return [$code, $msg, $vt->cost()];
            }
        }

        return [-2, "请重试！", $vt->cost()];
    }

    function xiao_an_ecu_acc_on($imei)
    {
        $vt = new vtimer();
        $hs = [
            'Content-Type: application/json',
            'xc-access-token:' . $this->get_xc_access_token($imei),
        ];

        $url = 'https://api.xiaoantech.com/ebike/v1/acc';
        $postdata = [
            'imei' => $imei,
            'acc' => 1,
            'agentId' => $this->get_agent_id($imei),
            'sn' => common::sn(),
        ];

        $result = common::curlpostjson($url, $postdata, $hs);
        if (empty($result)) {
            return [-1, "request error!", $vt->cost()];
        }

        if ($result['success'] == true) {
            if (isset($result['data']) && isset($result['data']['code'])) {
                list($code, $msg) = $this->code_to_msg($result['data']['code']);
                return [$code, $msg, $vt->cost()];
            }
        }

        return [-2, '请重试！', $vt->cost()];
    }

    function xiao_an_ecu_unlock($imei)
    {
        $vt = new vtimer();
        $hs = [
            'Content-Type: application/json',
            'xc-access-token: ' . $this->get_xc_access_token($imei),
        ];

        $url = 'https://api.xiaoantech.com/ebike/v1/lock';
        // $url = '127.0.0.1:8086/bike/unlock';
        //$url = '127.0.0.1:8086/bike/info';
        $postdata = [
            'imei' => $imei,
            'locked' => 0,
            'agentId' => $this->get_agent_id($imei),
            'sn' => common::sn(),
        ];
        $result = common::curlpostjson($url, $postdata, $hs);
        if (empty($result)) {
            return [-1, "request error!", $vt->cost()];
        }

        if ($result['success'] == true) {
            if (isset($result['data']) && isset($result['data']['code'])) {
                list($code, $msg) = $this->code_to_msg($result['data']['code']);
                return [$code, $msg, $vt->cost()];
            }
        }

        return [-2, '请重试！', $vt->cost()];
    }

    function query_device_info_rt($imei)
    {
        $vt = new vtimer();
        $hs = [
            'Content-Type: application/json',
            'xc-access-token: ' . $this->get_xc_access_token($imei),
        ];
        $url = "https://api.xiaoantech.com/ebike/v1/currentDeviceInfo";
        $postdata = [
            'imei' => $imei,
            'agentId' => $this->get_agent_id($imei),
        ];
        $result = common::curlgetjson($url, $postdata, $hs);
        if (empty($result)) {
            return null;
        }

        if ($result['success'] == true) {
            // var_dump($result);
            if (isset($result['data']) && isset($result['data']['code'])) {
                if ($result['data']['code'] == 0) {
                    $data = $result['data']['result'];
                    $loc = null;
                    $locate_type = null;
                    $updatetime = 0;
                    $speed = 0;
                    $course = 0;
                    if (isset($data['gps'])) {
                        $loc = $data['gps'];
                        $locate_type = 'gps';
                        $updatetime = $loc['timestamp'];
                        $speed = intval($loc['speed']);
                        $course = intval($loc['course']);
                    } else if (isset($data['lbs'])) {
                        //$loc = $data['lbs'];
                        // $locate_type = 'lbs';
                        //  $updatetime = $loc['timestamp'];
                    } else if (isset($data['cell'])) {
                        //  $loc = $this->cell_to_gps($data['cell']);
                        //  $locate_type = 'lbs';
                        //  $updatetime = time();
                    }

                    if ($loc) {
                        $info = [
                            'coordinate' => (new CoordConv())->wgs84togcj02([$loc['lng'], $loc['lat']]),
                            'gps_update_time' => date('Y-m-d H:i:s', $updatetime),
                            'locate_type' => $locate_type,
                            'speed' => $speed,
                            'course' => $course,
                        ];
                    }

                    $info['is_in_motion'] = intval($data['isWheelSpan']);
                    $info['is_on_battery'] = intval($data['powerState']);
                    $info['is_battery_locked'] = intval($data['seatLock']);
                    $info['is_wheel_locked'] = intval($data['wheelLock']);
                    $info['is_acc_on'] = intval($data['acc']);
                    $info['gsm_signal_strength'] = intval($data['gsm']);
                    $info['is_defend_on'] = intval($data['defend']);
                    if ($info['is_in_motion'] == 0 && $info['is_defend_on']) {
                        $info['battery_volt'] = intval($data['voltageMv']);
                    }
                    return $info;
                } else if ($result['data']['code'] == 109) {
                    $info = [
                        'is_online' => 0,
                    ];
                    return $info;
                }
            }
        }
        return null;
    }

    function unlock_battery($imei)
    {
        $vt = new vtimer();
        $hs = [
            'Content-Type: application/json',
            'xc-access-token: ' . $this->get_xc_access_token($imei),
        ];

        $url = 'https://api.xiaoantech.com/ebike/v1/batteryCompartment';
        // $url = '127.0.0.1:8086/bike/unlock';
        //$url = '127.0.0.1:8086/bike/info';
        $postdata = [
            'imei' => $imei,
            'locked' => 0,
            'agentId' => $this->get_agent_id($imei),
            'sn' => common::sn(),
        ];
        $result = common::curlpostjson($url, $postdata, $hs);
        if (empty($result)) {
            return [-1, "request error!", $vt->cost()];
        }

        if ($result['success'] == true) {
            if (isset($result['data']) && isset($result['data']['code'])) {
                list($code, $msg) = $this->code_to_msg($result['data']['code']);
                return [$code, $msg, $vt->cost()];
            }
        }

        return [-2, "请重试！", $vt->cost()];
    }

    /*
      1	锁车成功
      2 开锁成功
      3	开车成功
      4	锁车成功
      5	欢迎使用电单车
      6	欢迎使用电单车
      7 即将骑出服务区，车辆将自动断电
      8 你已骑出服务区，请立即返回
      9	我在这里
      10	滴滴滴滴
     */

    const XIAO_AN_VOICE_TYPE_OSVC_ALEADY = 12;
    const XIAO_AN_VOICE_TYPE_OSVC = 10;
    const XIAO_AN_VOICE_TYPE_RING = 9;
    const XIAO_AN_VOICE_TYPE_PARKWARN = 15;
    const XIAO_AN_VOICE_TYPE_OVERSPEED = 15;

    function device_voice($imei, $type)
    {
        $vt = new vtimer();
        $hs = [
            'Content-Type: application/json',
            'xc-access-token: ' . $this->get_xc_access_token($imei),
        ];

        $url = 'https://api.xiaoantech.com/ebike/v1/deviceVoice';
        // $url = '127.0.0.1:8086/bike/unlock';
        //$url = '127.0.0.1:8086/bike/info';
        $postdata = [
            'imei' => $imei,
            'locked' => 0,
            'agentId' => $this->get_agent_id($imei),
            'sn' => common::sn(),
            'index' => $type,
        ];

        $result = common::curlpostjson($url, $postdata, $hs);
        if (empty($result)) {
            return [-1, "request error!", $vt->cost()];
        }

        if ($result['success'] == true) {
            if (isset($result['data']) && isset($result['data']['code'])) {
                list($code, $msg) = $this->code_to_msg($result['data']['code']);
                return [$code, $msg, $vt->cost()];

            }
            return [-2, '请重试！', $vt->cost()];
        }

        return [-2, $result['error']['errormessage'], $vt->cost()];
    }

    function cell_to_gps($cell)
    {
        $hs = [
            'Content-Type: application/json',
            'xc-access-token: ' . $this->get_xc_access_token(null),
        ];

        $url = 'https://api.xiaoantech.com/ebike/v1/lbs2gps';
        // $url = '127.0.0.1:8086/bike/unlock';
        //$url = '127.0.0.1:8086/bike/info';
        $postdata = [
            'agentId' => $this->get_agent_id(null),
            'sn' => common::sn(),
            'cell' => $cell,
        ];


        $result = common::curlpostjson($url, $postdata, $hs);
        if ($result['success'] == true) {
            if (isset($result['data'])) {
                if (isset($result['data']['longitude']) && isset($result['data']['latitude'])) {
                    return [
                        'lng' => $result['data']['longitude'],
                        'lat' => $result['data']['latitude']
                    ];
                }
            }
        }
        return false;
    }

    function set_bluetooth($imei, $token, $name)
    {
        $vt = new vtimer();
        $hs = [
            'Content-Type: application/json',
            'xc-access-token: ' . $this->get_xc_access_token($imei),
        ];

        $url = 'https://api.xiaoantech.com/ebike/v1/bluetooth';
        // $url = '127.0.0.1:8086/bike/unlock';
        //$url = '127.0.0.1:8086/bike/info';
        $postdata = [
            'imei' => $imei,
            'agentId' => $this->get_agent_id($imei),
            'sn' => common::sn(),
        ];

        if ($token) {
            $postdata['token'] = $token;
        }
        if (!empty($name)) {
            $postdata['name'] = $name;
        }

        $result = common::curlpostjson($url, $postdata, $hs);
        if (empty($result)) {
            return [-1, "request error!", $vt->cost()];
        }

        if ($result['success'] == true) {
            if (isset($result['data']) && isset($result['data']['code'])) {
                list($code, $msg) = $this->code_to_msg($result['data']['code']);
                return [$code, $msg, $vt->cost()];
            }
            return [-2, '请重试！', $vt->cost()];
        }

        return [-2, $result['error']['errormessage'], $vt->cost()];
    }

    function get_track($imei, $start_time, $end_time)
    {
        $start_timestamp = strtotime($start_time);
        $end_timestamp = strtotime($end_time);
        $vt = new vtimer();
        $hs = [
            'Content-Type: application/json',
            'xc-access-token: ' . $this->get_xc_access_token($imei),
        ];
        $params = [
            'imei' => $imei,
            'agentId' => $this->get_agent_id($imei),
            'startTime' => $start_timestamp,
            'endTime' => $end_timestamp,
        ];
        $url = "https://api.xiaoantech.com/ebike/v1/GPSPoints";
        $result = common::curlgetjson($url, $params, $hs);
        if (empty($result)) {
            return FALSE;
        }

        if ($result['success'] == true) {
            if (isset($result['data'])) {
                $l = [];
                foreach ($result['data'] as $e) {
                    $coord = (new CoordConv())->wgs84togcj02([$e['lon'], $e['lat']]);
                    $l[] = [
                        $coord[0],
                        $coord[1],
                        date('Y-m-d H:i:s', $e['timestamp']),
                        !isset($e['speed']) ? 0 : $e['speed'],
                        !isset($e['course']) ? 0 : $e['course'],
                    ];
                }
                return $l;
            }
        }
        return false;
    }

    function move_limit($imei,$limit){
        $hs = [
            'Content-Type: application/json',
            'xc-access-token: ' . $this->get_xc_access_token(null),
        ];

        /*
         * {
            "imei": "865532048551440",
            "cmd": {
                "c": 32,
                "param": {
                    "isOverSpeedOn": 1
                }
            },
            "agentId": 313,
            "agentToken": "F82DFAFCACD3F69BEB2276CA7CC76B9B"
        }*/
        $url = 'https://api.xiaoantech.com/ebike/api/device';
        $postdata = [
            'imei' => $imei,
            'cmd' =>[
                'c'=>32,
                'param'=>[
                    'isOverSpeedOn'=>$limit,
                ]
            ],
            'sn' => common::sn(),
            'agentId' => $this->get_agent_id(null),
            'agentToken' => $this->get_xc_access_token(null),
        ];


        $result = common::curlpostjson($url, $postdata, $hs);
        if ($result['success'] == true) {
            if (isset($result['data'])) {
                return true;
            }
        }
        return false;
    }
}

class EcuLogModel
{

    function add($city_id, $bike_id, $data)
    {
        $key = "ECULOG|" . $city_id . "|" . $bike_id;
        if (is_array($data)) {
            $data = json_encode($data);
        }
        hiredis::db()->zAdd($key, common::time_ms(), $data);

        $r = rand(1, 50);
        if ($r == 1) {
            $count = hiredis::db()->zCard($key);
            if ($count > 1000) {
                hiredis::db()->zRemRangeByRank($key, 0, $count - 500);
            }
        }
    }

    function query($city_id, $bike_id, $start_time, $end_time, $pos, $limit)
    {
        $s = strtotime($start_time) * 1000;
        $e = strtotime($end_time) * 1000;

        $key = "ECULOG|" . $city_id . "|" . $bike_id;
        $ret = hiredis::db()->zRevRangeByScore($key, $e, $s, [
            'withscores' => false,
            'limit' => [$pos, $limit],
        ]);

        return $ret;
    }

    function count($city_id, $bike_id, $start_time, $end_time)
    {
        $s = strtotime($start_time) * 1000;
        $e = strtotime($end_time) * 1000;

        $key = "ECULOG|" . $city_id . "|" . $bike_id;
        $ret = hiredis::db()->zCount($key, $s, $e);
        return $ret;
    }

}
